package com.yykj.user.center.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;
import com.yykj.pay.center.client.dto.ClientPayConfigDTO;
import com.yykj.pay.center.client.feign.PayFeignClient;
import com.yykj.user.center.server.constant.Constant;
import com.yykj.user.center.server.form.GetOpenIdForm;
import com.yykj.user.center.server.service.WechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author chenl
 * @version 1.0
 * @date 2021/10/30 18:24
 */
@Slf4j
@Service
public class WechatServiceImpl implements WechatService {

    @Autowired
    PayFeignClient payFeignClient;

    @Override
    public String code2OpenId(GetOpenIdForm getOpenIdForm) {

        ClientPayConfigDTO clientPayConfigDTO = this.payFeignClient.get(getOpenIdForm.getHospitalId() + "");
        if (clientPayConfigDTO == null) {
            throw new RuntimeException("该医院配置不存在");
        }
        Map<String, String> data = new HashMap<String, String>();
        data.put("appid", clientPayConfigDTO.getClientAppId());
        data.put("secret", clientPayConfigDTO.getClientSecret());
        data.put("js_code", getOpenIdForm.getCode());
        data.put("grant_type", Constant.GRANTTYPE);

        String response = HttpRequest.get(Constant.WX_CODE2OPENID_URL).form(data).body();
        log.info("Response is:{} " + response);
        JSONObject obj = JSON.parseObject(response);//将json字符串转换为json对
        log.info("获取openid的返回值:{}", obj);
        return obj.getString("openid");
    }
/*
    @Override
    public String code2OpenId(GetOpenIdForm getOpenIdForm) {

        ClientPayConfigDTO clientPayConfigDTO = this.payFeignClient.get(getOpenIdForm.getHospitalId()+"");
        if(clientPayConfigDTO == null){
            throw new RuntimeException("该医院配置不存在");
        }
        String clientAppId = clientPayConfigDTO.getClientAppId();
        Map<String, String> data = new HashMap<String, String>();
        data.put("appid", Constant.APPID);
        data.put("secret", Constant.APP_SECRET);
        data.put("js_code", getOpenIdForm.getCode());
        data.put("grant_type", Constant.GRANTTYPE);

        String response = HttpRequest.get(Constant.WX_CODE2OPENID_URL).form(data).body();
        log.info("Response is:{} " + response);
        JSONObject obj= JSON.parseObject(response);//将json字符串转换为json对
        log.info("获取openid的返回值:{}",obj);
        return obj.getString("openid");
    }
*/
}
